/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<long long,int> s; //当前路径的所有前缀和
    int dfs(TreeNode* root,long long gain,int targetsum){
        if(!root){
            return 0;
        }

        int ret=0;
        long long newgain=gain+root->val; //当前获得
        if(s[newgain-targetsum]){ //如果可以通过之前的前缀和得到target
            ret+=s[newgain-targetsum];
        }
        s[newgain]++; //每种方法唯一

        ret+=dfs(root->left,gain+root->val,targetsum);
        ret+=dfs(root->right,gain+root->val,targetsum);

        s[newgain]--; //退出当前节点 需要减一 因为进入另一子树不可能经过当前子树
        return ret;
    }
    int pathSum(TreeNode* root, int targetsum) {
        s[0]=1;
        return dfs(root,0,targetsum);
    }
};